package org.example.tree.binary;

import org.example.tree.entity.BinaryTreeNode;

import javax.swing.tree.TreeNode;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author zjt
 * @description
 * @date 2024/1/30 10:01
 */
public class BinaryTreeTraversal {

    List<Integer> res = new ArrayList<>();

    public List<Integer> preorderTraversalA(BinaryTreeNode binaryTreeNode) {
        if (binaryTreeNode == null) {
            return res;
        }
        res.add(binaryTreeNode.root);
        preorderTraversalA(binaryTreeNode.left);
        preorderTraversalA(binaryTreeNode.right);
        return res;
    }

    public static void preorderTraversal(BinaryTreeNode binaryTreeNode) {
        if (binaryTreeNode == null) {
            return;
        }
        System.out.println(binaryTreeNode.root);
        preorderTraversal(binaryTreeNode.left);
        preorderTraversal(binaryTreeNode.right);
    }

    public static void inorderTraversal(BinaryTreeNode binaryTreeNode) {
        if (binaryTreeNode == null) {
            return;
        }
        inorderTraversal(binaryTreeNode.left);
        System.out.println(binaryTreeNode.root);
        inorderTraversal(binaryTreeNode.right);
    }

    public static void postorderTraversal(BinaryTreeNode binaryTreeNode) {
        if (binaryTreeNode == null) {
            return;
        }
        postorderTraversal(binaryTreeNode.left);
        postorderTraversal(binaryTreeNode.right);
        System.out.println(binaryTreeNode.root);
    }

    public static void levelOrderTraversal(BinaryTreeNode binaryTreeNode) {
        if (binaryTreeNode == null) {
            return;
        }
        //队列先进先出
        Queue<BinaryTreeNode> queue = new LinkedList<>();
        queue.offer(binaryTreeNode);
        while (!queue.isEmpty()) {
            BinaryTreeNode node = queue.poll();
            System.out.print(node.root + " ");
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
    }
}
